import React from 'react';
import { connect } from 'react-redux';
import SearchArea from 'components/search-area';
import { deepFullCopy, messages } from 'share/common';
import ResizeTable from 'components/resize-table';
import SlideFrame from 'components/slide-frame';
import Chooser from 'components/chooser';
import { Popover, Button, Form, Input, Switch, Icon, Message } from 'antd';
import './vehicle.css';
import ExportModal from 'components/template/export-modal/export-modal';
import vehicleService from './vehicle.service';
import menuRoute from 'routes/menuRoute';

const FormItem = Form.Item;

class Vehicle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      searchForm: [{
        type: 'select',
        id: 'del',
        label: messages('mcd.basicData.vehicle.is_Del'/* 启用状态 */),
        options: [{
          value: false,
          label: '启用'
        }, {
          value: true,
          label: '禁用'
        }],
        showSearch: true
      }, {
        type: 'input',
        id: 'carNumber',
        label: messages('mcd.basicData.vehicle.car_number'/* 车牌号 */),
        showSearch: true
      }, {
        type: 'select',
        id: 'public_flag',
        label: messages('mcd.basicData.vehicle.is_public'/* 是否公用 */),
        options: [{
          value: false,
          label: '否'
        }, {
          value: true,
          label: '是'
        }],
        showSearch: true
      }, {
        type: 'input',
        id: 'driverName',
        label: messages('mcd.basicData.vehicle.driv'/* 司机 */),
        showSearch: true
      }, {
        type: 'input',
        id: 'employeeName',
        label: messages('mcd.basicData.vehicle.employee_id' /* 审批人 */),
        showSearch: true
      }],
      columns: [{
        width: '10%',
        title: messages('common.sequence' /* 序号 */),
        key: 'order',
        dataIndex: 'order',
        render: text => text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={text}>{text}</Popover> : <span>-</span>
      }, {
        width: '20%',
        title: messages('mcd.basicData.vehicle.car_number' /* 车牌号 */),
        key: 'carNumber',
        dataIndex: 'carNumber',
        render: text => text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={text}>{text}</Popover> : <span>-</span >
      }, {
        width: '15%',
        title: messages('mcd.basicData.vehicle.driv' /* 司机 */),
        key: 'driverName',
        dataIndex: 'driverName',
        render: (text, record, index) => text ? <Popover
          className="tableText"
          overlayStyle={{ maxWidth: 500 }}
          placement="topLeft" content={record.driverName}>{record.driverName}</Popover> : <span>-</span >
      }, {
        width: '15%',
        title: messages('mcd.basicData.vehicle.employee_id' /* 审批人 */),
        key: 'employeeId',
        dataIndex: 'employeeId',
        render: (text, record, index) => text ? <Popover
          className="tableText"
          overlayStyle={{ maxWidth: 500 }}
          placement="topLeft" content={record.employeeName}>{record.employeeName}</Popover> : <span>-</span >
      }, {
        width: '10%',
        title: messages('mcd.basicData.vehicle.is_public' /* 是否公用 */),
        key: 'public_flag',
        dataIndex: 'public_flag',
        render: (text, record, index) => {
          if ([true, false].includes(text)) {
            if (!text) {
              return <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={'否'}>否</Popover>;
            }
            return <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={'是'}>是</Popover>;
          }
          return <span>-</span >;
        }
      }, {
        width: '10%',
        title: messages('mcd.basicData.vehicle.is_Del' /* 启用状态 */),
        key: 'del',
        dataIndex: 'del',
        render: (text) => {
          if ([true, false].includes(text)) {
            if (!text) {
              return <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={'启用'}>启用</Popover>;
            }
            return <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={'禁用'}>禁用</Popover>;

          }
          return <span>-</span >;
        }
      }, {
        width: '20%',
        title: messages('common.operation' /* 操作 */),
        key: 'action',
        dataIndex: 'action',
        render: (text, record) => {
          if (record.driv && record.driverName) {
            return (
              <div>
                <span className="tableText editText disableText">修改</span>
                <a className="tableText" href="javascript:void(0);" onClick={() => this.handleOnAbleOrDisable(record)}>{!record.del ? '禁用' : '启用'}</a>
                <a className="tableText" style={{ display: 'inline-block', marginLeft: '20px' }} href="javascript:void(0);" onClick={() => this.gotoDetail(record)}>详情</a>
              </div>
            )
          }
          return (
            <div>
              <a className="tableText editText" href="javascript:void(0);" onClick={() => this.handleOnEdit(record)}>修改</a>
              <a className="tableText" href="javascript:void(0);" onClick={() => this.handleOnAbleOrDisable(record)}>{!record.del ? '禁用' : '启用'}</a>
              <a className="tableText" style={{ display: 'inline-block', marginLeft: '20px' }} href="javascript:void(0);" onClick={() => this.gotoDetail(record)}>详情</a>
            </div>
          )
        }
      }],
      originData: [],
      data: [],
      pagination: {
        pageSize: 10,
        current: 1,
        page: 0,
        total: 0,
        size: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      selectedRecord: {},
      actionType: '',
      visible: false,
      loading: true,
      slideFrameKey: 'slideFrameKey0',
      exportAble: true,
      searchCondition: { all: true }, // all: true(没有筛选条件) false(有筛选条件)
      saveBtnLoading: false // 保存按钮的loading状态
    };
  }

  componentDidMount() {
    this.getListData();
  }

  /**
   * 根据关键字和页码去查询车辆信息
   * @param {Object} values
   */
  getListData = async (valuesParams = {}) => {
    const values = deepFullCopy(valuesParams);
    const { pagination } = this.state;
    let url = '';
    url = `?size=${pagination.size}&page=${pagination.page}`;
    for (const key in values) {
      if (values[key]) {
        url += `&${key}=${values[key]}`;
      } else if (!values[key]) {
        delete values[key];
      }
    }
    const paginationTemp = Object.assign({}, pagination);
    try {
      const res = await vehicleService.getListData(url);
      const dataTemp = res.data.records.map((record, index) => {
        record.order = index + 1;
        return record;
      });
      paginationTemp.total = res.data.total;
      this.setState({
        data: dataTemp,
        pagination: paginationTemp,
        loading: false
      });
    } catch (err) {
      paginationTemp.total = 0;
      this.setState({
        data: [],
        pagination: paginationTemp,
        loading: false
      });
    }
  }

  /**
   * 重置搜索框
   * values：搜索表单的所有组件的值
   */
  clearHandle = () => {
    const { pagination } = this.state;
    this.setState({
      loading: true,
      pagination: {
        pageSize: pagination.pageSize,
        current: 1,
        page: 0,
        size: pagination.size,
        total: pagination.total
      },
      searchCondition: { all: true }
    }, () => {
      this.getListData();
    });
  }
  /**
   * 搜索表单的搜索事件
   * values：搜索表单的所有组件的值
   */
  handleSearch = (values) => {
    const { pagination } = this.state;
    const searchCondition = {};
    searchCondition.isDel = values.del;
    searchCondition.isPublic = values.public_flag;
    searchCondition.carNumber = values.carNumber;
    searchCondition.driverName = values.driverName;
    searchCondition.employeeName = values.employeeName;
    const downloadCondition = {};
    downloadCondition.all = false;
    downloadCondition.del = values.del;
    downloadCondition.publicFlag = values.public_flag;
    downloadCondition.carNumber = values.carNumber;
    downloadCondition.driverName = values.driverName;
    downloadCondition.employeeName = values.employeeName;
    this.setState({
      loading: true,
      pagination: {
        pageSize: pagination.pageSize,
        current: 1,
        page: 0,
        size: pagination.size,
        total: pagination.total
      },
      searchCondition: downloadCondition
    }, () => {
      this.getListData(searchCondition);
    });
  }

  /**
   * 点击显示编辑抽屉
   * 1、显示右侧编辑抽屉
   * 2、根据接口获取这一条数据的详细信息并填充到编辑抽屉内部的表单
   * @param {Object} record
   */
  handleOnEdit = (record) => {
    const { slideFrameKey } = this.state;
    let driver = null
    if (record.vendor && record.driverName) {
      driver = {
        vnlgnm: record.driverName,
        vendor: record.vendor
      }
    }
    this.props.form.setFieldsValue({
      carNumber: record.carNumber,
      driv: driver ? [driver] : [],
      employeeId: [{ employeeID: record.employeeId, fullName: record.employeeName }],
      public_flag: record.public_flag
    });
    this.setState({
      actionType: 'edit',
      selectedRecord: record,
      visible: true,
      slideFrameKey: slideFrameKey + 1
    });
  }

  /**
   * 点击触发禁用或者启用操作
   * @param {Object} record
   */
  handleOnAbleOrDisable = (record) => {
    if ([false, true].includes(record.del)) {
      if (!record.del) {
        this.setState({
          loading: true
        }, () => {
          this.handleOnDisable(record);
        });
      } else {
        this.setState({
          loading: true
        }, () => {
          this.handleOnAble(record);
        });
      }
    } else {
      console.error('是否启用状态为空');
    }
  }

  /**
   * 调用禁用接口
   * @param {String} record
   */
  handleOnDisable = async (recordParam) => {
    const { searchCondition } = this.state;
    const record = deepFullCopy(recordParam);
    record.del = true;
    try {
      const res = await vehicleService.updateData(record);
      Message.success(messages('setting.key2815')); // 禁用成功
      this.setState({
        loading: true
      }, () => {
        this.getListData(searchCondition);
      });
    } catch (err) {
      this.setState({
        loading: false
      })
    }
  }

  /**
   * 调用启用接口
   * @param {String} record
   */
  handleOnAble = async (recordParam) => {
    const { searchCondition } = this.state;
    const record = deepFullCopy(recordParam);
    record.del = false;
    try {
      const res = await vehicleService.updateData(record);
      Message.success(messages('setting.key2814')); // 启用成功
      this.setState({
        loading: true
      }, () => {
        this.getListData(searchCondition);
      });
    } catch (err) {
      this.setState({
        loading: false
      })
    }
  }

  /**
   * 修改每页最大显示数据数量、页码跳转触发
   * @param {Object} pagination
   * @param {*} filters
   * @param {*} sorter
   */
  onChangePage = (pagination, filters, sorter) => {
    const { searchCondition } = this.state;
    this.setState({
      pagination: {
        pageSize: pagination.pageSize,
        current: pagination.current,
        page: pagination.current - 1,
        size: pagination.pageSize,
        total: pagination.total
      },
      loading: true
    }, () => {
      this.getListData(searchCondition);
    });
  }

  /**
   * 新增车辆信息
   * 显示右侧新增抽屉
   */
  handleOnAdd = () => {
    const { slideFrameKey } = this.state;
    this.setState({
      actionType: 'add',
      visible: true,
      selectedRecord: {},
      slideFrameKey: slideFrameKey + 1
    }, () => {
      this.props.form.setFieldsValue({
        carNumber: '',
        driv: [],
        employeeId: '',
        public_flag: false
      });
    });
  }

  /**
   * 渲染编辑抽屉
   */
  renderEditAndAdd = () => {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14, offset: 1 },
    };

    return (
      <div>
        <Form onSubmit={this.handleOnCreateAndEdit}>
          <FormItem
            {...formItemLayout}
            label={messages('mcd.basicData.vehicle.car_number' /* 车牌号 */)}
          >
            {getFieldDecorator('carNumber', {
              initialValue: '',
              rules: [{ required: true, message: messages('common.can.not.be.empty', { name: messages('mcd.basicData.vehicle.car_number' /* 车牌号 */) }) }]
            })(
              <Input placeholder={messages('common.please.enter')} />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label={messages('mcd.basicData.vehicle.driv' /* 司机 */)}
          >
            {getFieldDecorator('driv', {
              initialValue: [],
              rules: [{ required: false }]
            })(
              <Chooser
                disabled={true}
                single
                placeholder={messages('common.please.select')}
                labelKey="vnlgnm"
                valueKey="vendor"
                type="mcd_driver"
              />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label={messages('mcd.basicData.vehicle.employee_id' /* 审批人 */)}
          >
            {getFieldDecorator('employeeId', {
              initialValue: [],
              rules: [{ required: true, message: messages('common.can.not.be.empty', { name: messages('mcd.basicData.vehicle.employee_id' /* 审批人 */) }) }]
            })(
              <Chooser
                single
                placeholder={messages('common.please.select')}
                labelKey="fullName"
                valueKey="employeeID"
                type="user"
              />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label={messages('mcd.basicData.vehicle.is_public' /* 是否公用 */)}
          >
            {this.state.selectedRecord.public_flag ? <span className="isPublicText">是</span> : <span className="isPublicText">否</span>}
            {getFieldDecorator('public_flag', {
              initialValue: false,
              rules: [{ required: false, message: messages('common.can.not.be.empty', { name: messages('mcd.basicData.vehicle.is_public' /* 是否公用 */) }) }]
            })(
              <Switch
                checkedChildren={<Icon type="check" />}
                unCheckedChildren={<Icon type="close" />}
                onChange={(checked) => {
                  const tempSelectedRecord = this.state.selectedRecord;
                  tempSelectedRecord.public_flag = checked;
                  this.setState({ selectedRecord: tempSelectedRecord });
                }
                }
                checked={this.state.selectedRecord.public_flag}
              />
            )}
          </FormItem>
          <div className="slide-footer">
            <Button loading={this.state.saveBtnLoading} type="primary" htmlType="submit">{messages('common.save')}</Button>
            <Button onClick={this.handleOnHideSlide}>{messages('common.cancel')}</Button>
          </div>
        </Form>
      </div>
    );
  }

  /**
   * 点击保存按钮触发
   * 1、处理用户填入的数据
   * 2、根据actionType判断调用保存接口还是修改接口
   */
  handleOnCreateAndEdit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { actionType, selectedRecord } = this.state;
        const result = Object.assign({}, values);
        console.log('result', result)
        result.vnvndr = result.driv.length > 0 ? result.driv[0].vnvndr : null;
        result.driverName = result.driv.length > 0 ? result.driv[0].vnlgnm : null;
        result.driv = result.driv.length > 0 ? result.driv[0].id : null;
        result.employeeId = result.employeeId[0].employeeID;
        result.public_flag = result.public_flag;
        result.del = false;
        result.id = selectedRecord.id;
        switch (actionType) {
          case 'edit':
            this.editFun(result);
            break;
          case 'add':
            this.addFun(result);
            break;
          default:
            console.error('未知操作');
            break;
        }
      }
    });
  }

  handleOnHideSlide = () => {
    this.setState({
      visible: false
    });
  }

  /**
   * 调用编辑接口
   */
  editFun = async (values) => {
    const { searchCondition } = this.state;
    this.setState({
      saveBtnLoading: true
    }, async () => {
      try {
        const res = await vehicleService.updateData(values);
        this.setState({
          visible: false,
          loading: true,
          saveBtnLoading: false
        }, () => {
          this.getListData(searchCondition);
        });
      } catch (err) {
        this.setState({
          saveBtnLoading: false
        })
      }
    })
  }

  /**
   * 调用保存接口
   * @param {Object} values
   */
  addFun = async (values) => {
    const { searchCondition } = this.state;
    this.setState({
      saveBtnLoading: true
    }, async () => {
      try {
        const res = await vehicleService.addRecord(values);
        this.setState({
          visible: false,
          loading: true,
          saveBtnLoading: false
        }, () => {
          this.getListData(searchCondition);
        });
      } catch (err) {
        this.setState({
          saveBtnLoading: false
        })
      }
    })
  }

  gotoDetail = (record) => {
    console.log("record", record)
    let path = menuRoute.getRouteItem('vehicle-detail', 'key').url.replace(':id', record.id);
    this.context.router.push(path);
  }

  render() {
    return (
      <div className={'vehiclePage'}>
        <SearchArea
          searchForm={this.state.searchForm}
          clearHandle={this.clearHandle}
          submitHandle={this.handleSearch}
        />
        <div className="totalNum">
          {messages('common.total', { total: `${this.state.pagination.total}` })}
        </div>
        <div className="btnsContainer">
          <Button className="addBtn" type="primary" onClick={() => this.handleOnAdd()}>{messages('supplier.key203')}</Button>
          <ExportModal
            type="btn"
            exportTitle={messages('setting.key302')}
            exportType="CAR"
            exportCommand={'CAR'}
            exportCondition={{ carDownloadCommand: this.state.searchCondition }}
          />
        </div>
        <ResizeTable
          rowKey={'id'}
          dataSource={this.state.data}
          loading={this.state.loading}
          pagination={this.state.pagination}
          onChange={this.onChangePage}
          columns={this.state.columns}
          size="middle"
          bordered
        />
        <SlideFrame
          slideFrameKey={this.state.slideFrameKey}
          title={messages('mcd.basicData.vehicle.edit')}
          width={'730px'}
          show={this.state.visible}
          content={this.renderEditAndAdd}
          afterClose={this.handleCloseSlide}
          onClose={this.handleOnHideSlide}
        // params={slideFrame.params}
        />
      </div >
    );
  }
}

Vehicle.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    organization: state.budget.organization,
    company: state.login.company,
    language: state.main.language,
    tenantMode: state.main.tenantMode
  };
}

export default connect(mapStateToProps)(Form.create()(Vehicle));
